//首页
'use strict';
import React, {Component} from 'react';
import Header from '../common/header'
import * as URLconstant from '../constant/URLconstant';
import Util from '../common/util'
import VideoIndex from './videoIndex'
import Modal from 'react-native-modalbox'
import Icon from 'react-native-vector-icons/Ionicons'
import {
    View,
    Text,
    ScrollView,
    TouchableOpacity,
    FlatList,
    StyleSheet,
    Image,
} from 'react-native';
import WebView from 'react-native-webview'


export default class videoList extends Component {
    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            cateList: [],
            cate_id: '',
            page: 1,
            limit: 10,
            isOver: false,
            again: true,
            loaded: false,
            videoList: null,
            loadedVideo: false,
            isOpen: false
        };
        this.renderFooter = this.renderFooter.bind(this)
        this.onEndReached = this.onEndReached.bind(this)
        this._renderRow = this._renderRow.bind(this)
    }

    componentDidMount() {
        this.getVideoClass()
    }

    getVideoClass() {
        let url = URLconstant.GET_VIDEO_CATE
        let datakey = []
        Util.get(url, datakey, (datas) => {
            if (datas.status == 0) {
                let data = datas.data
                this.setState({
                    cateList: data,
                    cate_id: data[0].id,
                    loaded: true
                })
                this.getVideoList(data[0].id)
            }
        }, (err) => {

        })
    }


    getVideoList(cate_id) {
        if (!cate_id) {
            cate_id = this.state.cate_id
        }
        let url = URLconstant.GET_VIDEO_LIST
        let datakey = []
        datakey['page'] = this.state.page
        datakey['limit'] = this.state.limit
        datakey['cate_id'] = cate_id
        Util.get(url, datakey, (datas) => {
            let loadedVideo = true
            let hasVideo = false
            if (datas.status == 0) {
                hasVideo = true
                let again = true
                let isOver = false
                let limit = this.state.limit
                let newList = datas.data
                let videoList = this.state.videoList;
                if (videoList == null) {
                    videoList = []
                }
                if (newList.length < limit) {
                    again = false
                    isOver = true
                }
                Array.prototype.push.apply(videoList, newList);
                this.setState({
                    isOver: isOver,
                    again: again,
                    videoList: videoList
                })
            }
            this.setState({
                loadedVideo: loadedVideo,
                hasVideo: hasVideo
            })
        }, (err) => {

        })
    }

    async selectCate(cate_id) {
        await this.setState({
            cate_id: cate_id,
            page: 1,
            limit: 10,
            isOver: false,
            again: true,
            videoList: [],
            loadedVideo: false
        })
        this.getVideoList(cate_id)
    }

    showHeader() {
        let cateList = this.state.cateList
        let cate_id = this.state.cate_id
        return (
            <View style={{height: 40, borderBottomColor: '#e0e0e0', borderBottomWidth: 1, backgroundColor: "#fff"}}>
                <ScrollView horizontal={true} style={styles.cate_header}>
                    {
                        cateList.map((item, index) => {
                            return (
                                <TouchableOpacity style={cate_id == item.id ? styles.select_item : styles.cate_item}
                                                  key={index} onPress={() => this.selectCate(item.id)}>
                                    <Text style={cate_id == item.id ? {fontSize: 14, color: "#f00"} : {
                                        fontSize: 14,
                                        color: "#333"
                                    }}>{item.title}</Text>
                                </TouchableOpacity>
                            )
                        })
                    }
                </ScrollView>
            </View>
        )
    }

    renderFooter() {
        return (
            <View style={{height: 30, alignItems: 'center', justifyContent: 'center', width: Util.size.width}}>
                <Text style={{fontSize: 12, color: "#969696"}}>{this.state.isOver ? "没有更多数据了" : "正在加载中"}</Text>
            </View>
        )
    }

    async onEndReached() {
        if (this.state.again) {
            await  this.setState({
                page: this.state.page + 1
            })
            this.getVideoList()
        }
    }

    playVideo(uri, title) {
        this.uri = uri
        this.title = title
        this.setState({
            isOpen: true
        })
    }

    _renderRow = ({item}) => {
        return (
            <TouchableOpacity
                onPress={() => this.playVideo(item.link, item.title)}
                style={styles.video_item} key={item.id}>
                <Image
                    source={item.picture ? {uri: item.picture} : require('../imgs/video_bg.png')}
                    resizeMode={'cover'}
                    style={styles.video_img}
                />
                <View style={{paddingVertical: 10}}>
                    <Text>{item.title}</Text>
                </View>
            </TouchableOpacity>
        )
    }

    showVideoPlay() {
        let uri = 'https://v.qq.com/txp/iframe/player.html?vid=' + this.uri + '&autoplay=true'
        let HTML = `
<!DOCTYPE>
<html style="width:100%;height:100%">
  <head>
    <title>Hello Static World</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">
  </head>
  <style>
  html,body,div,iframe{padding:0;margin:0;}
</style>
  <body style="width:100%;height:100%;">
  <div>
 <iframe height=` + Util.size.height + ` width=` + Util.size.width + ` src='` + uri + `' frameborder=0></iframe>
</div>
  </body>
</html>
`;
        return (
            <Modal
                isOpen={this.state.isOpen}
                backdropPressToClose={false} swipeToClose={false}
                style={styles.videoModal}
                animationDuration={0}
                position={'bottom'}
            >
                <WebView
                    source={{html: HTML}}
                    automaticallyAdjustContentInsets={false}
                    style={{width:Util.size.width,height:200,flex:1}}
                />
                <View style={{
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    zIndex: 999999999,
                    width: Util.size.width,
                    height: 50,
                    alignItems: 'center',
                    justifyContent: 'center'
                }}>
                    <Text style={{fontSize: 14, color: "#f0f"}}>{this.title}</Text>
                    <TouchableOpacity
                        onPress={() => this.setState({isOpen: false})}
                        style={{
                            width: 50,
                            height: 50,
                            alignItems: 'center',
                            justifyContent: 'center',
                            position: 'absolute',
                            top: 0,
                            left: 0
                        }}>
                        <Icon name={"ios-close-circle-outline"} size={25} color={'#f0f'}/>
                    </TouchableOpacity>
                </View>
            </Modal>
        )
    }


    render() {
        return (
            <View style={{flex: 1, backgroundColor: "#f3f4f9"}}>
                <Header navigation={this.props.navigation} title={'视频介绍'}/>
                {
                    !this.state.loaded ?
                        <View style={{flex: 1}}>
                            {Util.loading()}
                        </View> :
                        <View style={{flex: 1}}>
                            {this.showHeader()}
                            {
                                !this.state.loadedVideo ?
                                    <View style={{flex: 1}}>
                                        {Util.loading()}
                                    </View> :
                                    <View style={{flex: 1}}>
                                        {
                                            !this.state.hasVideo ?
                                                <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
                                                    <Text>没有视频</Text>
                                                </View> :
                                                <FlatList
                                                    style={{paddingTop: 10}}
                                                    numColumns={2}
                                                    data={this.state.videoList}
                                                    renderItem={this._renderRow}
                                                    onEndReached={this.onEndReached.bind(this)}
                                                    keyExtractor={item => item.id}
                                                    ListFooterComponent={this.renderFooter}
                                                />
                                        }
                                    </View>
                            }
                        </View>
                }
                {this.showVideoPlay()}
            </View>
        )
    }
}
var styles = StyleSheet.create({
    cate_header: {
        flexDirection: 'row',
        width: Util.size.width,
        height: 40,
    },
    cate_item: {
        height: 39,
        alignItems: 'center',
        justifyContent: 'center',
        paddingHorizontal: 15,
        borderBottomWidth: 1,
        borderBottomColor: 'transparent',
        marginHorizontal: 15
    },
    select_item: {
        height: 39,
        alignItems: 'center',
        justifyContent: 'center',
        paddingHorizontal: 15,
        borderBottomWidth: 1,
        borderBottomColor: '#f00',
        marginHorizontal: 15
    },
    video_list: {
        flexDirection: 'row',
        alignItems: "center",
        flexWrap: 'wrap',
        marginBottom: 10,
        paddingHorizontal: 10,
        paddingVertical: 10
    },
    video_item: {
        width: (Util.size.width - 30) / 2,
        marginBottom: 10,
        backgroundColor: "#fff",
        alignItems: 'center',
        marginLeft: 10
    },
    video_img: {
        width: (Util.size.width - 30) / 2,
        height: (Util.size.width - 30) / 2
    },
    videoModal: {
        width: Util.size.width,
        height: Util.size.height - 100,
        alignItems: 'center',
        justifyContent: 'center',
    }
})